<template>
  <div class="resources-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>资源管理</h2>
        <p>管理系统中的所有资源文件</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showUploadDialog = true">
          <el-icon><Upload /></el-icon>
          上传资源
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-filter-section">
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索资源名称、描述或上传者..."
          clearable
          @keyup.enter="handleSearch"
          class="search-input"
        >
          <template #prefix>
            <el-icon><search /></el-icon>
          </template>
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </div>
      
      <div class="filter-bar">
        <div class="filter-item">
          <span class="filter-label">分类：</span>
          <el-select v-model="categoryFilter" placeholder="选择分类" @change="handleFilter" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="category in categories"
              :key="category.categoryId"
              :label="category.categoryName"
              :value="category.categoryId"
            ></el-option>
          </el-select>
        </div>
        
        <div class="filter-item">
          <span class="filter-label">状态：</span>
          <el-select v-model="statusFilter" placeholder="审核状态" @change="handleFilter" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="已审核" value="APPROVED"></el-option>
            <el-option label="待审核" value="PENDING"></el-option>
            <el-option label="已拒绝" value="REJECTED"></el-option>
          </el-select>
        </div>
        
        <div class="filter-item">
          <span class="filter-label">文件类型：</span>
          <el-select v-model="typeFilter" placeholder="文件类型" @change="handleFilter" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="PDF" value="pdf"></el-option>
            <el-option label="Word" value="doc,docx"></el-option>
            <el-option label="PPT" value="ppt,pptx"></el-option>
            <el-option label="视频" value="mp4,avi,mkv"></el-option>
            <el-option label="音频" value="mp3,wav"></el-option>
          </el-select>
        </div>
        
        <div class="filter-item">
          <span class="filter-label">排序：</span>
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleFilter">
            <el-option label="最新上传" value="uploadTime"></el-option>
            <el-option label="下载量" value="downloadCount"></el-option>
            <el-option label="文件大小" value="fileSize"></el-option>
            <el-option label="评分" value="rating"></el-option>
          </el-select>
        </div>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon total">
          <el-icon><folder /></el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ stats.total }}</div>
          <div class="stat-label">总资源数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon approved">
          <el-icon><circle-check /></el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ stats.approved }}</div>
          <div class="stat-label">已审核</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon pending">
          <el-icon><warning /></el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ stats.pending }}</div>
          <div class="stat-label">待审核</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon downloads">
          <el-icon><download /></el-icon>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ (stats.totalDownloads || 0).toLocaleString() }}</div>
          <div class="stat-label">总下载量</div>
        </div>
      </div>
    </div>

    <!-- 资源列表 -->
    <div class="resources-table">
      <el-table
        v-loading="loading"
        :data="resources"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        
        <!-- ID列已隐藏 -->
        <!-- <el-table-column prop="resourceId" label="ID" width="80" sortable="custom"></el-table-column> -->
        
        <el-table-column label="资源信息" min-width="250">
          <template #default="{ row }">
            <div v-if="row" class="resource-info">
              <div class="file-icon">
                <el-icon><component :is="getFileIcon(row.fileType)" /></el-icon>
              </div>
              <div class="resource-details">
                <div class="resource-title">{{ row.title }}</div>
                <div class="resource-meta">
                  <span class="file-type">{{ row.fileType?.toUpperCase() }}</span>
                  <span class="file-size">{{ formatFileSize(row.fileSize) }}</span>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="categoryName" label="分类" width="120">
          <template #default="{ row }">
            <el-tag v-if="row" size="small" type="primary">{{ row.categoryName }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="uploaderName" label="上传者" width="120"></el-table-column>
        
        <el-table-column prop="uploadTime" label="上传时间" width="120" sortable="custom">
          <template #default="{ row }">
            <span v-if="row">{{ formatDate(row.uploadTime) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="downloadCount" label="下载量" width="100" sortable="custom">
          <template #default="{ row }">
            <span v-if="row">{{ row.downloadCount || 0 }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="rating" label="综合评分" width="120">
          <template #default="{ row }">
            <div v-if="row" class="rating-display">
              <el-rate
                :value="formatRating(row.rating)"
                disabled
                size="small"
                show-score
                text-color="#ff9900"
                :max="5"
              />
              <span class="rating-text">{{ formatRatingText(row.rating) }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row" :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <div v-if="row" class="action-buttons">
              <el-button size="small" @click="editResource(row)">
                <el-icon><edit /></el-icon>
                编辑
              </el-button>
              <el-dropdown @command="handleMoreAction">
                <el-button size="small">
                  更多
                  <el-icon><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{action: 'approve', resource: row}" v-if="row.status === 'PENDING'">
                      <el-icon><circle-check /></el-icon>
                      审核通过
                    </el-dropdown-item>
                    <el-dropdown-item :command="{action: 'reject', resource: row}" v-if="row.status === 'PENDING'">
                      <el-icon><circle-close /></el-icon>
                      审核拒绝
                    </el-dropdown-item>
                    <el-dropdown-item :command="{action: 'download', resource: row}">
                      <el-icon><download /></el-icon>
                      下载文件
                    </el-dropdown-item>
                    <el-dropdown-item :command="{action: 'delete', resource: row}" divided>
                      <el-icon><delete /></el-icon>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 批量操作 -->
      <div v-if="selectedResources.length > 0" class="batch-actions">
        <span class="selected-count">已选择 {{ selectedResources.length }} 项</span>
        <el-button @click="batchApprove">批量审核</el-button>
        <el-button @click="batchReject">批量拒绝</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 上传资源对话框 -->
    <el-dialog
      v-model="showUploadDialog"
      title="上传新资源"
      width="600px"
      @close="resetUploadForm"
    >
      <el-form :model="uploadForm" :rules="uploadRules" ref="uploadFormRef" label-width="100px">
        <el-form-item label="资源标题" prop="title">
          <el-input v-model="uploadForm.title" placeholder="请输入资源标题" />
        </el-form-item>
        
        <el-form-item label="资源描述" prop="description">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入资源描述"
          />
        </el-form-item>
        
        <el-form-item label="资源分类" prop="categoryId">
          <el-select v-model="uploadForm.categoryId" placeholder="请选择分类">
            <el-option
              v-for="category in categories"
              :key="category.categoryId"
              :label="category.categoryName"
              :value="category.categoryId"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="上传文件" prop="file">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            :file-list="fileList"
            action="#"
            drag
          >
            <el-icon><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">
                支持 PDF、Word、PPT、视频、音频等格式，文件大小不超过 100MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showUploadDialog = false">取消</el-button>
        <el-button type="primary" @click="submitUpload" :loading="uploading">
          上传资源
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑资源对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑资源信息"
      width="500px"
      @close="resetEditForm"
    >
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="资源标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入资源标题" />
        </el-form-item>
        
        <el-form-item label="资源描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入资源描述"
          />
        </el-form-item>
        
        <el-form-item label="资源分类" prop="categoryId">
          <el-select v-model="editForm.categoryId" placeholder="请选择分类">
            <el-option
              v-for="category in categories"
              :key="category.categoryId"
              :label="category.categoryName"
              :value="category.categoryId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="submitEdit" :loading="editing">
          保存修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Upload, 
  Download, 
  Search, 
  Folder, 
  CircleCheck, 
  Warning, 
  Edit, 
  ArrowDown, 
  CircleClose, 
  Delete, 
  UploadFilled,
  Document,
  DocumentCopy,
  Present,
  VideoPlay,
  Headset,
  Picture,
  FolderOpened
} from '@element-plus/icons-vue'
import request from '@/utils/request'

export default {
  name: 'Resources',
  components: {
    Upload,
    Download,
    Search,
    Folder,
    CircleCheck,
    Warning,
    Edit,
    ArrowDown,
    CircleClose,
    Delete,
    UploadFilled,
    Document,
    DocumentCopy,
    Present,
    VideoPlay,
    Headset,
    Picture,
    FolderOpened
  },
  setup() {
    // 响应式数据
    const loading = ref(false)
    const resources = ref([])
    const categories = ref([])
    const selectedResources = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(20)
    
    // 搜索和筛选
    const searchKeyword = ref('')
    const categoryFilter = ref('')
    const statusFilter = ref('')
    const typeFilter = ref('')
    const sortBy = ref('uploadTime')
    const sortOrder = ref('desc')
    
    // 统计数据
    const stats = ref({
      total: 0,
      approved: 0,
      pending: 0,
      totalDownloads: 0
    })
    
    // 对话框
    const showUploadDialog = ref(false)
    const showEditDialog = ref(false)
    const uploading = ref(false)
    const editing = ref(false)
    const uploadFormRef = ref()
    const editFormRef = ref()
    const uploadRef = ref()
    const fileList = ref([])
    
    // 表单数据
    const uploadForm = reactive({
      title: '',
      description: '',
      categoryId: '',
      file: null
    })
    
    const editForm = reactive({
      resourceId: null,
      title: '',
      description: '',
      categoryId: ''
    })
    
    // 表单验证规则
    const uploadRules = {
      title: [
        { required: true, message: '请输入资源标题', trigger: 'blur' },
        { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入资源描述', trigger: 'blur' },
        { min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
      ],
      categoryId: [
        { required: true, message: '请选择资源分类', trigger: 'change' }
      ]
    }
    
    const editRules = {
      title: [
        { required: true, message: '请输入资源标题', trigger: 'blur' },
        { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入资源描述', trigger: 'blur' },
        { min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
      ],
      categoryId: [
        { required: true, message: '请选择资源分类', trigger: 'change' }
      ]
    }
    
    // 方法
    const loadResources = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          size: pageSize.value,
          keyword: searchKeyword.value,
          categoryId: categoryFilter.value,
          status: statusFilter.value,
          fileType: typeFilter.value,
          sortBy: sortBy.value,
          sortOrder: sortOrder.value
        }
        
        const response = await request.get('admin/resources', { params })
        resources.value = response.data.records || []
        total.value = response.data.total || 0
      } catch (error) {
        // 加载资源失败日志已移除
        ElMessage.error('加载资源失败，请稍后重试')
        resources.value = []
        total.value = 0
      } finally {
        loading.value = false
      }
    }
    
    const loadCategories = async () => {
      try {
        const response = await request.get('categories')
        categories.value = response.data || []
      } catch (error) {
        // 加载分类失败日志已移除
        categories.value = []
      }
    }
    
    const loadStats = async () => {
      try {
        const response = await request.get('admin/resources/stats')
        stats.value = {
          total: response.data?.totalResources || 0,
          approved: response.data?.approvedResources || 0,
          pending: response.data?.pendingResources || 0,
          totalDownloads: response.data?.totalDownloads || 0
        }
      } catch (error) {
        // 加载统计数据失败日志已移除
        stats.value = {
          total: 0,
          approved: 0,
          pending: 0,
          totalDownloads: 0
        }
      }
    }
    
    const handleSearch = () => {
      currentPage.value = 1
      loadResources()
    }
    
    const handleFilter = () => {
      currentPage.value = 1
      loadResources()
    }
    
    const handleSizeChange = (size) => {
      pageSize.value = size
      loadResources()
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadResources()
    }
    
    const handleSelectionChange = (selection) => {
      selectedResources.value = selection
    }
    
    const handleSortChange = ({ prop, order }) => {
      sortBy.value = prop
      sortOrder.value = order === 'ascending' ? 'asc' : 'desc'
      loadResources()
    }
    

    
    const editResource = (resource) => {
      editForm.resourceId = resource.resourceId
      editForm.title = resource.title
      editForm.description = resource.description
      editForm.categoryId = resource.categoryId
      showEditDialog.value = true
    }
    
    const handleMoreAction = ({ action, resource }) => {
      switch (action) {
        case 'approve':
          approveResource(resource)
          break
        case 'reject':
          rejectResource(resource)
          break
        case 'download':
          downloadResource(resource)
          break
        case 'delete':
          deleteResource(resource)
          break
      }
    }
    
    const approveResource = async (resource) => {
      try {
        await request.put(`admin/resources/${resource.resourceId}/approve`)
        ElMessage.success('审核通过')
        loadResources()
      } catch (error) {
        // 审核失败日志已移除
        ElMessage.error('审核失败，请稍后重试')
      }
    }
    
    const rejectResource = async (resource) => {
      try {
        await ElMessageBox.prompt('请输入拒绝理由', '审核拒绝', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder: '请输入拒绝理由...'
        })
        
        await request.put(`admin/resources/${resource.resourceId}/reject`)
        ElMessage.success('已拒绝')
        loadResources()
      } catch (error) {
        if (error !== 'cancel') {
          // 拒绝失败日志已移除
          ElMessage.error('操作失败，请稍后重试')
        }
      }
    }
    
    const downloadResource = async (resource) => {
      try {
        const response = await request.get(`resources/${resource.resourceId}/download`, {
          responseType: 'blob'
        })
        
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', `${resource.title}.${resource.fileType}`)
        document.body.appendChild(link)
        link.click()
        link.remove()
        window.URL.revokeObjectURL(url)
        
        ElMessage.success('下载成功')
      } catch (error) {
        // 下载失败日志已移除
        ElMessage.error('下载失败，请稍后重试')
      }
    }
    
    const deleteResource = async (resource) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除资源 "${resource.title}" 吗？此操作不可恢复。`,
          '删除确认',
          {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await request.delete(`admin/resources/${resource.resourceId}`)
        ElMessage.success('删除成功')
        loadResources()
      } catch (error) {
        if (error !== 'cancel') {
          // 删除失败日志已移除
          ElMessage.error('删除失败，请稍后重试')
        }
      }
    }
    
    const batchApprove = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要批量审核通过选中的 ${selectedResources.value.length} 个资源吗？`,
          '批量审核',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
          }
        )
        
        const ids = selectedResources.value.map(r => r.resourceId)
        await request.put('admin/resources/batch-approve', { ids })
        ElMessage.success('批量审核成功')
        loadResources()
      } catch (error) {
        if (error !== 'cancel') {
          // 批量审核失败日志已移除
          ElMessage.error('批量审核失败，请稍后重试')
        }
      }
    }
    
    const batchReject = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要批量拒绝选中的 ${selectedResources.value.length} 个资源吗？`,
          '批量拒绝',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const ids = selectedResources.value.map(r => r.resourceId)
        await request.put('admin/resources/batch-reject', { ids })
        ElMessage.success('批量拒绝成功')
        loadResources()
      } catch (error) {
        if (error !== 'cancel') {
          // 批量拒绝失败日志已移除
          ElMessage.error('批量拒绝失败，请稍后重试')
        }
      }
    }
    
    const batchDelete = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要批量删除选中的 ${selectedResources.value.length} 个资源吗？此操作不可恢复。`,
          '批量删除',
          {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const ids = selectedResources.value.map(r => r.resourceId)
        await request.delete('admin/resources/batch-delete', { data: { ids } })
        ElMessage.success('批量删除成功')
        loadResources()
      } catch (error) {
        if (error !== 'cancel') {
          // 批量删除失败日志已移除
          ElMessage.error('批量删除失败，请稍后重试')
        }
      }
    }
    

    
    const handleFileChange = (file) => {
      uploadForm.file = file.raw
    }
    
    const beforeUpload = (file) => {
      const allowedTypes = ['pdf', 'doc', 'docx', 'ppt', 'pptx', 'mp4', 'avi', 'mkv', 'mp3', 'wav']
      const fileExtension = file.name.split('.').pop().toLowerCase()
      
      if (!allowedTypes.includes(fileExtension)) {
        ElMessage.error('不支持的文件格式')
        return false
      }
      
      const maxSize = 100 * 1024 * 1024 // 100MB
      if (file.size > maxSize) {
        ElMessage.error('文件大小不能超过 100MB')
        return false
      }
      
      return false // 阻止自动上传
    }
    
    const submitUpload = async () => {
      if (!uploadFormRef.value) return
      
      try {
        await uploadFormRef.value.validate()
        
        if (!uploadForm.file) {
          ElMessage.error('请选择要上传的文件')
          return
        }
        
        uploading.value = true
        
        const formData = new FormData()
        formData.append('title', uploadForm.title)
        formData.append('description', uploadForm.description)
        formData.append('categoryId', uploadForm.categoryId)
        formData.append('file', uploadForm.file)
        
        await request.post('admin/resources/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        ElMessage.success('上传成功')
        showUploadDialog.value = false
        resetUploadForm()
        loadResources()
        loadStats()
      } catch (error) {
        // 上传失败日志已移除
        ElMessage.error('上传失败，请稍后重试')
      } finally {
        uploading.value = false
      }
    }
    
    const submitEdit = async () => {
      if (!editFormRef.value) return
      
      try {
        await editFormRef.value.validate()
        editing.value = true
        
        await request.put(`admin/resources/${editForm.resourceId}`, {
          title: editForm.title,
          description: editForm.description,
          categoryId: editForm.categoryId
        })
        
        ElMessage.success('修改成功')
        showEditDialog.value = false
        resetEditForm()
        loadResources()
      } catch (error) {
        // 修改失败日志已移除
        ElMessage.error('修改失败，请稍后重试')
      } finally {
        editing.value = false
      }
    }
    
    const resetUploadForm = () => {
      uploadForm.title = ''
      uploadForm.description = ''
      uploadForm.categoryId = ''
      uploadForm.file = null
      fileList.value = []
      if (uploadFormRef.value) {
        uploadFormRef.value.resetFields()
      }
      if (uploadRef.value) {
        uploadRef.value.clearFiles()
      }
    }
    
    const resetEditForm = () => {
      editForm.resourceId = null
      editForm.title = ''
      editForm.description = ''
      editForm.categoryId = ''
      if (editFormRef.value) {
        editFormRef.value.resetFields()
      }
    }
    
    // 工具方法
    const getFileIcon = (fileType) => {
      if (!fileType) return 'Document'
      const type = fileType.toLowerCase()
      if (['pdf'].includes(type)) return 'Document'
      if (['doc', 'docx'].includes(type)) return 'DocumentCopy'
      if (['ppt', 'pptx'].includes(type)) return 'Present'
      if (['mp4', 'avi', 'mkv'].includes(type)) return 'VideoPlay'
      if (['mp3', 'wav'].includes(type)) return 'Headset'
      if (['jpg', 'jpeg', 'png', 'gif'].includes(type)) return 'Picture'
      if (['zip', 'rar', '7z'].includes(type)) return 'FolderOpened'
      return 'Document'
    }
    
    const getStatusTagType = (status) => {
      switch (status) {
        case 'APPROVED': return 'success'
        case 'PENDING': return 'warning'
        case 'REJECTED': return 'danger'
        default: return 'info'
      }
    }
    
    const getStatusText = (status) => {
      switch (status) {
        case 'APPROVED': return '已审核'
        case 'PENDING': return '待审核'
        case 'REJECTED': return '已拒绝'
        default: return '未知状态'
      }
    }
    
    const formatFileSize = (bytes) => {
      if (!bytes || bytes === undefined || bytes === null) return '0 B'
      if (typeof bytes !== 'number' || isNaN(bytes)) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return ''
      try {
        const date = new Date(dateString)
        if (isNaN(date.getTime())) return ''
        return date.toLocaleDateString('zh-CN')
      } catch (error) {
        // 日期格式化错误日志已移除
        return ''
      }
    }

    // 格式化评分为1-5分制
    const formatRating = (rating) => {
      if (!rating || rating === undefined || rating === null) return 0
      // 确保评分在1-5范围内
      const numRating = Number(rating)
      if (isNaN(numRating)) return 0
      return Math.max(1, Math.min(5, numRating))
    }

    // 格式化评分文本显示
    const formatRatingText = (rating) => {
      const formattedRating = formatRating(rating)
      if (formattedRating === 0) return '暂无评分'
      return `${formattedRating.toFixed(1)}/5.0`
    }
    
    // 生命周期
    onMounted(async () => {
      // 延迟执行以确保DOM完全准备好
      await new Promise(resolve => setTimeout(resolve, 100))
      
      try {
        await Promise.all([
          loadCategories(),
          loadResources(),
          loadStats()
        ])
      } catch (error) {
        // 初始化数据加载失败日志已移除
      }
    })
    
    return {
      // 响应式数据
      loading,
      resources,
      categories,
      selectedResources,
      total,
      currentPage,
      pageSize,
      searchKeyword,
      categoryFilter,
      statusFilter,
      typeFilter,
      sortBy,
      sortOrder,
      stats,
      showUploadDialog,
      showEditDialog,
      uploading,
      editing,
      uploadFormRef,
      editFormRef,
      uploadRef,
      fileList,
      uploadForm,
      editForm,
      uploadRules,
      editRules,
      
      // 方法
      handleSearch,
      handleFilter,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      handleSortChange,
      editResource,
      handleMoreAction,
      batchApprove,
      batchReject,
      batchDelete,
      handleFileChange,
      beforeUpload,
      submitUpload,
      submitEdit,
      resetUploadForm,
      resetEditForm,
      getFileIcon,
      getStatusTagType,
      getStatusText,
      formatFileSize,
      formatDate,
      formatRating,
      formatRatingText
    }
  }
}
</script>

<style scoped>
.resources-management {
  background: #f5f5f5;
  min-height: 100vh;
  padding: 20px;
}

/* 页面头部 */
.page-header {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.header-left p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 12px;
}

/* 搜索筛选区域 */
.search-filter-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-bar {
  margin-bottom: 16px;
}

.search-input {
  max-width: 400px;
}

.filter-bar {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-label {
  font-weight: 500;
  color: #606266;
  white-space: nowrap;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stat-icon .el-icon {
  font-size: 24px;
}

.stat-icon.total { background: linear-gradient(135deg, #667eea, #764ba2); }
.stat-icon.approved { background: linear-gradient(135deg, #67c23a, #85ce61); }
.stat-icon.pending { background: linear-gradient(135deg, #e6a23c, #f56c6c); }
.stat-icon.downloads { background: linear-gradient(135deg, #409eff, #2d8cf0); }

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

/* 资源表格 */
.resources-table {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.resource-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-icon {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  background: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.file-icon .el-icon {
  font-size: 18px;
}

.resource-details {
  flex: 1;
  min-width: 0;
}

.resource-title {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.resource-meta {
  display: flex;
  gap: 8px;
  font-size: 12px;
  color: #909399;
}

.file-type {
  background: #e1f3d8;
  color: #67c23a;
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: 500;
}

.file-size {
  color: #909399;
}

.rating-display {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
}

.rating-text {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

/* 批量操作 */
.batch-actions {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.selected-count {
  color: #606266;
  font-weight: 500;
}

/* 分页 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 对话框内容 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-upload-dragger) {
  border-radius: 6px;
  border: 2px dashed #d9d9d9;
  background: #fafafa;
  transition: all 0.3s ease;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409eff;
  background: #f0f7ff;
}

:deep(.el-upload-dragger .el-icon) {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

:deep(.el-upload__text) {
  color: #606266;
  font-size: 14px;
}

:deep(.el-upload__tip) {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .resources-management {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .header-right {
    width: 100%;
    justify-content: flex-end;
  }
  
  .filter-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .filter-item {
    justify-content: space-between;
  }
  
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .batch-actions {
    flex-wrap: wrap;
  }
}

@media (max-width: 480px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .resource-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .action-buttons {
    flex-wrap: wrap;
  }
}

/* 动画效果 */
@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.stat-card {
  animation: slideInUp 0.6s ease forwards;
}

.stat-card:nth-child(1) { animation-delay: 0.1s; }
.stat-card:nth-child(2) { animation-delay: 0.2s; }
.stat-card:nth-child(3) { animation-delay: 0.3s; }
.stat-card:nth-child(4) { animation-delay: 0.4s; }
</style> 